package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishPageQueryDTO;
import com.sky.dto.SetmealDTO;
import com.sky.dto.SetmealPageQueryDTO;
import com.sky.entity.Category;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.exception.SetmealEnableFailedException;
import com.sky.mapper.CategoryMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.SetmealService;
import com.sky.vo.DishItemVO;
import com.sky.vo.DishVO;
import com.sky.vo.SetmealVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Slf4j
@Service
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealMapper setmealMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private DishMapper dishMapper;

    /**
     * 新增套餐，同时插入套餐菜品关联 N：N
     * @param dto
     */
    @Transactional
    public void insert(SetmealDTO dto) {
        //1、填充套餐基本信息
        //自动填充字段。在mapper层弄
        //设置初始状态为0
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(dto, setmeal);
        setmeal.setStatus(StatusConstant.DISABLE);
        setmealMapper.insert(setmeal);
        //2、拿到刚插入的套餐id;(这个要在setmealMapper中设置返回主键才能拿到)
        Long setmealId = setmeal.getId();
        //3、准备套餐-菜品表的数据
        List<SetmealDish> dishes = dto.getSetmealDishes();
        dishes.forEach(dish ->{
            dish.setSetmealId(setmealId);
        });
        //4、批量插入套餐-菜品关系
        setmealDishMapper.batchInsert(dishes);

        log.info("新增套餐 [{}] 及其 {} 道菜品关系插入完成", dto.getName(), dishes.size());
    }

    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public PageResult page(SetmealPageQueryDTO dto) {
        //1、设置分页参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        //2、调用mapper列表查询方法，强转成page
        Page<SetmealVO> page = setmealMapper.page(dto);
        //3、封装pageresult对象并返回
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 根据套餐id查询套餐信息
     * @param id
     * @return
     */
    @Override
    public SetmealVO getById(Long id) {
        SetmealVO vo = new SetmealVO();
        //1、根据id查套餐信息，并赋值给vo
        Setmeal setmeal= setmealMapper.getById(id);
        BeanUtils.copyProperties(setmeal,vo);
        Category category = categoryMapper.getById(setmeal.getCategoryId());
        vo.setCategoryName(category.getName());
        //2、查询套餐-菜品关系列表，赋值给vo
        List<SetmealDish> dishes = setmealDishMapper.getBySetmealId(id);
        vo.setSetmealDishes(dishes);
        return vo;
    }

    /**
     * 修改套餐信息
     * @param dto
     */
    @Transactional //涉及2个表的修改
    public void update(SetmealDTO dto) {
        //1、修改套餐信息表，需要用到update的自动填充
        Setmeal setmeal = new Setmeal();
        BeanUtils.copyProperties(dto, setmeal);
        setmealMapper.update(setmeal);

        //2、修改套餐-菜品列表，先删除后插入
        setmealDishMapper.delectBatchBySetmealId(dto.getId());
        List<SetmealDish> dishes = dto.getSetmealDishes();//需要填充套餐id，因为前端传过来的是没有id的
        Long setmealId = setmeal.getId();
        //3、准备套餐-菜品表的数据
        dishes.forEach(dish ->{
            dish.setSetmealId(setmealId);
        });
        setmealDishMapper.batchInsert(dishes);
    }

    /**
     * 起售停售状态修改
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {
        if(status == StatusConstant.ENABLE){ //如果传入的状态为要起售，则走下面逻辑
            List<SetmealDish> setmealDish = setmealDishMapper.getBySetmealId(id);
            setmealDish.forEach(sd->{
                //套餐内如果有停售菜品，则套餐无法上架
                Dish dish = dishMapper.selectById(sd.getDishId());
                if (dish.getStatus() == StatusConstant.DISABLE) {
                    throw new SetmealEnableFailedException(MessageConstant.SETMEAL_ENABLE_FAILED);
                }
            });
        }
        Setmeal setmeal = new Setmeal();
        setmeal.setStatus(status);
        setmeal.setId(id);
        setmealMapper.update(setmeal);
    }

    @Transactional
    public void delete(List<Long> ids) {
        // 1、判断套餐是否在售，如果是，不可删除套餐
        ids.forEach(id->{
            Setmeal setmeal = setmealMapper.getById(id);
            if (setmeal.getStatus() == StatusConstant.ENABLE) {
                throw new DeletionNotAllowedException(MessageConstant.SETMEAL_ON_SALE);
            }
        });

        // 2、删除套餐信息
        setmealMapper.deletBatch(ids);

        //3、删除套餐-菜品关联信息
        ids.forEach(id->{
            setmealDishMapper.delectBatchBySetmealId(id);
        });

    }

    /**
     * 条件查询菜品
     * @param setmeal
     * @return
     */
    @Override
    public List<Setmeal> list(Setmeal setmeal) {
        return setmealMapper.list(setmeal);
    }

    /**
     * 根据id查询菜品选项
     * @param id
     * @return
     */
    public List<DishItemVO> getDishItemById(Long id) {
        return setmealMapper.getDishItemBySetmealId(id);
    }

}

